<?php

/**
 *  合同管理
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/10/27
 * Time: 10:02
 */

namespace app\api\controller\contractmanage;

use think\Controller;
use PhpOffice\PhpWord\TemplateProcessor;
use app\api\controller\common\CommonPlus;
use think\Db;
use think\Request;
// use think\console\command\make\Controller;


class Contractmgr extends Controller
{

    // <s></s>
    protected $admin;
    protected $model = null;
    protected $statusArr = [0=>'未处理',1=>'通过',2=>'拒绝'];
    protected $backArr = [0=>'未回传',1=>'已回传'];
    public function _initialize()
    {
        $this->admin = session('admin');
        $this->model = model('Contractmgr');
    }

    /**
     * 合同管理列表页
     * 模糊查询需后补 暂时先做普版 原先
     */
    public function contractList999()
    {
        //var_dump(23);die;
        $keyword = input('keyword');
        $id_zs = input('id_zs'); // 展商id
        $id_zhui = input('id_zhui'); //展会id
        $page = input('page');
        $where = array();
        $page = max(1, intval($page));
        $pagesize = 10;

        $where['is_delete'] = 0;
        if (!empty($id_zs)) {
            $where['id_zs'] =  $id_zs;
        }
        if (!empty($id_zhui)) {
            $where['id_zhui'] =  $id_zhui;
        }


        if (!empty($keyword)) {
            $where['name_zs'] = array('like', '%' . $keyword . '%');
        }

        $list = $this->model->listWherePage($where, 'id desc', ($page - 1) * $pagesize, $pagesize);
        $total = $this->model->countWhere($where);

        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list, 'total' => $total, 'countpage' => ceil($total / $pagesize)]]);
    }

    /**
     * 合同列表 多关联
     */
    public function contractList(){
        $exhibition = $this->request->param('exhibition');
        if(empty($exhibition)){
            return json(['code'=>-1,'msg'=>'缺少关键主键展会id']);
        }
        $keyword=$this->request->param('keyword');
        $keyword = isset($keyword) && $keyword != '' ? $keyword : '';
        $status = $this->request->param('status');
        $status = isset($status) && $status != '' ? $status : -1;
        $page = $this->request->param('page');
        $page = isset($page) && $page != '' ? $page : 1;
        $back = input('back');
        $back = isset($back) && $back != '' ? $back : -1;
        $member_id = input('member_id');
        $member_id = isset($member_id) && $member_id != '' ? $member_id : '';
        $pageSize = input('pageSize');
        $pageSize = isset($pageSize) && $pageSize != '' ? $pageSize : 10;
        $tabName=$this->getTabName($exhibition);
        $where['h.is_delete'] = 0;
        $where['h.htmodel'] = array(array('neq','null'),array('neq',''), 'or');;
        if(!empty($exhibition)){
            $where['h.id_zhui'] = $exhibition;
        }

        if(!empty($member_id)){
            $where['h.create_uid'] = $member_id;
        }

        if(!empty($keyword)){
            $where['h.name_zs']=array('like','%'.$keyword.'%');
//            $comRes=db($tabName)->field('id')->where(['company_name'=>array('like','%'.$keyword.'%')])->select();
//            if(!empty($comRes)){
//                $ids=[];
//                foreach ($comRes as &$v){
//                    $ids[]=$v['id'];
//                }
//                $where['h.id_zs'] = array('in',implode(',',$ids));
//            }
        }

        if(is_numeric($back)&&$back>=0){
            $where['h.is_back'] = $back;
        }

        if(is_numeric($status)&&$status>=0){
            if($status == 0){
                $where['h.htmodel_admin'] = array(array('eq',null),array('eq',''), 'or');;
            }else if($status == 1){
                $where['h.htmodel_admin'] = array(array('neq',null),array('neq',''), 'or');;
            }else if($status == 2){
                $where['h.s_status'] = 1;
            }

        }

        // if(is_numeric($member_id)&&$member_id>0){ 暂时不加需要再加
        //     $where['h.create_uid'] = $member_id;
        // }else{
        //     //当前用户权限
        //     $role_id = db('admin_role')->where(['admin_id'=>$this->admin['id']])->value('role_id');
        //     if(!$role_id && $this->admin['is_super']==0){
        //         return json(['code'=>0,'msg'=>'角色不存在']);
        //     }
        //     $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
        //     if($this->admin['is_super'] == 1){
        //         //不加限制条件
        //     }else{
        //         if($is_gl == 1){
        //             $w['org_id_tree'] = ['like', "%".$this->admin['org_id']."%"];
        //             //所有所属组织的用户 id
        //             $adminarr =db('admin')->field('id')->where($w)->select();
        //             $admin_ids = array_column($adminarr,'id');
        //             $where['h.create_uid'] = array('in',$admin_ids);
        //         }else{
        //             $where['h.create_uid'] = $this->admin['id'];
        //         }
        //     }
        // }


        $page = max(1,intval($page));
        $list = db('contract')
            ->alias('h')
            ->field('h.*,e.id exhibition_id,e.title,a.realname,z.company_name')
            ->join('exhibition e','h.id_zhui=e.id','left')
            ->join('admin a','h.create_uid=a.id','left')
            ->join($tabName.' z','h.id_zs=z.id','left')
            ->where($where)
            ->order('h.id desc')
            ->limit(($page-1)*$pageSize.','.$pageSize)
            ->select();

        $total = db('contract')
            ->alias('h')
            ->field('h*,e.id as exhibition_id,e.name,a.realname')
            ->join('exhibition e','h.id_zhui=e.id','left')
            ->join('admin a','h.create_uid=a.id','left')
            ->where($where)
            ->count();

        if(!empty($list)){
            foreach ($list as &$v){
                $ftotal=db('finance')->field('sum(fee) as f_total')->where(['contract_id'=>$v['id'],'is_delete'=>0])->select();
                $v['f_total'] =  empty($ftotal)?0:$ftotal[0]['f_total'];
            }
            unset($v);
        }

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);

    }
    /**
     * 合同基本信息
     * 这边应该也会关联很多  后续考虑 stj
     * @return \think\response\Json|void
     */
    public function contractDetail()
    {
        $com = new CommonPlus();
        $id = input('id');

        $where['id'] = $id;
        //$where['is_delete'] = 0;
        $info = $this->model->findWhere($where);

        // 获取 D表
        $where1 = array('mid' => $id,'is_delete'=>0);
        $r1 = $com->sel_com_fxlist("f", $where1, "contract_detail");
        $info['D_detail'] = $r1; // 表单的明细

        $r2 = $com->sel_com_fxlist("f", $where1, "contract_detail_plan");
        $info['plan_detail'] = $r2; // 付款计划 明细条数
        // var_dump($r1);die;

        return json(['code' => 1, 'msg' => 'success', 'data' => $info]);
    }


    /**
     * 新增合同
     * 缺少文件转doc
     * 具体要实现什么样的》》》
     * 2：应该还需要合同的明细表
     *
     * @return \think\response\Json|void
     */
    public function addContract()
    {
        $com = new CommonPlus();

        //==common
        $create_uid = $this->admin['id'];
        $remark = input('remark');
        //== comon
        $name_zs = input('name_zs'); //展商名称:
        $id_zs = input('id_zs'); //展商id
        $model_id = input('model_id'); // 获取选择的合同模版
        $id_zhui = input('id_zhui'); //展会id
        $temp=db('contract_mould_yc')->where(['id'=>$model_id])->find();
        if(!$temp){
            return json(['code' => 0, 'msg' => '操作失败，未上传模板']);
        }
        if(empty($id_zs)){
            return json(['code' => 0, 'msg' => '操作失败，未选择展商']);
        }
        if(empty($id_zhui)){
            return json(['code' => 0, 'msg' => '操作失败，未选择展会']);
        }
        $id_zwei = input('id_zwei'); //展位id
        if(empty($id_zwei)){
            return json(['code' => 0, 'msg' => '请选择展位']);
        }
        $rBooth=db('booth')->where(['is_delete'=>0,'id'=>array('in',$id_zwei)])->field('id,agent_id')->select();
        if(count($rBooth)!=count(explode(',',$id_zwei))){
            return json(['code' => 0, 'msg' => '操作失败，展位错误']);
        }

        $flag=true;
        foreach($rBooth as &$v){
            if($id_zs!=$v['agent_id']){
                $flag=false;
                break;
            }
        }
        if($flag == false){
            return json(['code' => 0, 'msg' => '展商绑定展位错误']);
        }

        $addr = input('addr');
        $tel = input('tel');
        $fax = input('fax');  // 传真
        $people_jinban = input('people_jinban'); //经办人
        $type_canzhan = input('type_canzhan'); // 参展展品类别
        $ht_id = input('ht_id'); // 合同编号
        $ht_name = input('ht_name'); // 合同名称
        $people_qianyue = input('people_qianyue'); // 签约人
        $customername = input('customername'); // 客户名称
        $ht_time = strtotime(input('ht_time')); // 合同日期
        $ht_time_endpay = strtotime(input('ht_time_endpay')); // 付款截止日期
        $money_total_xiangmu = input('money_total_xiangmu'); // 项目总金额
        $money_zhuce = input('money_zhuce'); // 注册费
        $money_total_ht = input('money_total_ht'); // 合同总金额
        $pay_planname = input('pay_planname'); // 付款计划名称
        $money_pay_one = input('money_pay_one'); // 单笔支付
        $money_pay_total_fk = input('money_pay_total_fk'); // 付款总额
        $time_pay_endfk = strtotime(input('time_pay_endfk')); // 付款截至日期
        $per_fk = input('per_fk'); // 付款比例
        $corner_price = input('corner_price'); // 付款比例

        $link=input('link'); // 网址
        $positions_cn=input('positions_cn'); // 职位
        $email_person=input('email_person'); // email
        $business_type=input('business_type'); // 公司性质
        $mobile_person=input('mobile_person'); // 移动电话
        $postcode=input('postcode'); // 移动电话
        $data = array(
            'create_uid' => $create_uid, 'remark' => $remark, 'create_time' => time(),'model_id'=>$model_id,'corner_price'=>$corner_price,'postcode'=>$postcode,
            'name_zs' => $name_zs, 'id_zs' => $id_zs, 'id_zhui' => $id_zhui, 'id_zwei'=>$id_zwei,'addr' => $addr, 'tel' => $tel, 'fax' => $fax,
            'people_jinban' => $people_jinban, 'type_canzhan' => $type_canzhan, 'ht_id' => $temp['template_code'].$id_zhui.$id_zs, 'ht_name' => $ht_name, 'people_qianyue' => $people_qianyue,
            'customername' => $customername, 'ht_time' => $ht_time, 'ht_time_endpay' => $ht_time_endpay, 'money_total_xiangmu' => $money_total_xiangmu, 'money_zhuce' => $money_zhuce,
            'money_total_ht' => $money_total_ht, 'pay_planname' => $pay_planname, 'money_pay_one' => $money_pay_one, 'money_pay_total_fk' => $money_pay_total_fk, 'time_pay_endfk' => $time_pay_endfk,
            'per_fk' => $per_fk,'is_back'=>0,'s_status'=>0,'link' => $link,'positions_cn'=>$positions_cn,'email_person'=>$email_person,'business_type'=>$business_type,'mobile_person'=>$mobile_person
        );
//        var_dump($data);die();
        $r = $this->model->insertData($data);
        if (!$r) {
            return json(['code' => 0, 'msg' => '合同保存操作失败，请重试']);
        }
        $tabName=$this->getTabName($id_zhui);
        $zsData = db($tabName)->where(['id'=>$id_zs])->find();
        if(!$zsData){
            return json(['code'=>0,'msg'=>'展商数据错误,操作失败，请重试']);
        }
        if($zsData['status']<4){
            $zsRes=db($tabName)->where(['id'=>$id_zs])->update(['status'=>4]);
            if(!$zsRes){
                return json(['code'=>0,'msg'=>'展商数据更新失败，请重试']);
            }
        }
        $com->contractLog($id_zhui,'合同新增',$id_zs,1);
        // //添加关联的合同表中----李  晨--建立
        // $datas['contract_id'] = $r;
        // $datas['exhibition_id'] = $id_zhui;
        // $datas['booth_id'] = $id_zwei;
        // $datas['company_id'] = $id_zs;
        // $datas['member_id'] = $create_uid;
        // $datas['is_pay'] = 0;
        // $datas['status'] = 0;
        // $datas['back'] = 0;
        // $datas['create_time'] = time();
        // $rDatas = model('CompanyFollowContract')->insertData($datas);
        // if(!$rDatas){
        //     return json(['code'=>0,'msg'=>'操作失败，请重试']);
        // }



        // 明细 开始

        /**
         * 服务类别  下拉框 还是文本框？？？
         * sort 是永远 递增
         */
        // 测试
        // $detaildata11 = array(
        //     array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "2.00", "price_sale" => "7", "discount" => "1.5", "num" => "10", "price_prate" => "2", "price_count" => "110", "remark" => "remark"),
        //     array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "30.00", "price_sale" => "8", "discount" => "1.2", "num" => "20", "price_prate" => "3", "price_count" => "115", "remark" => "remark"),
        //     array("pro_name" => "pro_name1", "type1_name" => "type1_name1", "type_service" => "type_service1", "price" => "40.00", "price_sale" => "9", "discount" => "1.3", "num" => "30", "price_prate" => "5", "price_count" => "98", "remark" => "remark"),
        // );

        //增加明细   包含更新
        //  $detaildata1 = input('D_detail'); // 数组
        // $detaildata = json_decode(json_encode(($detaildata22)),TRUE);
        // $detaildata = json_decode($detaildata1, TRUE);
        // var_dump($detaildata);die;
        //$detaildata = 0;
        // $z_id = $r; // 主id
        // if (is_array($detaildata)) {
        //     $i = 0;
        //     foreach ($detaildata as $item) {
        //         $i++;
        //         $data_d = array(
        //             'mid' => $z_id, 'sortid' => $i, 'pro_name' => $item['pro_name'], 'type1_name' => $item['type1_name'],'isck' => $item['isck'],
        //             //'type_serviceid' => $item['type_serviceid'],
        //             'type_service' => $item['type_service'], 'price' => $item['price'],
        //             'price_sale' => $item['price_sale'], 'discount' => $item['discount'], 'num' => $item['num'], 'price_prate' => $item['price_prate'],
        //             'price_count' => $item['price_count'], 'remark' => $item['remark']
        //         );
        //         $r1 = $this->model->insertData_D($data_d, 'contract_detail'); //暂未定


        //     }
        // }


        // 明细end

        // 计划明细
        // $plan_detail22 = array(
        //     array("plan_name" => "plan_name", "money_db" => "11", "money_total" => "20", "time_fked" => "111", "per_fk" => "7" ),
        //     array("plan_name" => "plan_name", "money_db" => "11", "money_total" => "20", "time_fked" => "111", "per_fk" => "8" ),
        // );

        //增加明细   包含更新  计划 表 不一样

        // $plan_detail = json_decode(json_encode(($plan_detail22)),TRUE); // ces
        // $plan_detail1 = input('plan_detail'); // 数组
        // $plan_detail = json_decode($plan_detail1, TRUE);
        //$detaildata = 0;
        // $z_id = $r; // 主id
        // if (is_array($plan_detail)) {
        //     $i = 0;
        //     foreach ($plan_detail as $item) {
        //         $i++;
        //         $data_d = array(
        //             'mid' => $z_id, 'sortid' => $i, 'plan_name' => $item['plan_name'], 'money_db' => $item['money_db'],
        //             'money_total' => $item['money_total'], 'time_fked' => strtotime($item['time_fked']), 'per_fk' => $item['per_fk']
        //         );
        //         $r2 = $this->model->insertData_D($data_d, 'contract_detail_plan'); // coms


        //     }
        // }
        // 明细end

        // 0404 测试  查询展位


        // $where = array('id' => $id_zwei);
        // $rzw = $com->sel_com_fxlist("f", $where, "booth");

        // // $pricezh=$com->convertAmountToCn($rzw[0]['price'],0);
        // $pricezhdax=$com->inttod($rzw[0]['price'],0);
        // $zspara=array('id_zs'=>$id_zs); // zhans
        // $info_zs= $com->getinfo_zs( $zspara);// 展商id...

        // // 0404

        // // 根据模版 转doc 2：回头在更新主表new file

        // if (!empty($htmodel)) {
        //     $data['htmodel'] = $htmodel;
        //     $data['z_id'] = $r;
        //     // 0404
        //     // 展商信息 可能又重复数组 覆盖，排查
        //     $data['company_name'] = $info_zs[0]['company_name']; //
        //     $data['company_name_en'] = $info_zs[0]['company_name_en']; //
        //     $data['company_address'] = $info_zs[0]['company_address']; //
        //     $data['company_yb'] = $info_zs[0]['company_yb']; //   邮编
        //     $data['link'] = $info_zs[0]['link']; //
        //     $data['salesman'] = $info_zs[0]['salesman']; //   负责人 暂时业务员
        //     $data['positions'] = $info_zs[0]['positions']; //    职务
        //     $data['tel'] = $info_zs[0]['tel']; //
        //     $data['mobile'] = $info_zs[0]['mobile']; //
        //     $data['fax_person'] = $info_zs[0]['fax_person']; //     传真
        //     $data['email'] = $info_zs[0]['email']; //


        //     //2
        //     $data['area'] = $rzw[0]['area']; // 面积
        //     $data['price'] = $rzw[0]['price'];
        //     $data['price_count'] = $rzw[0]['price'];
        //     $data['price_daxie'] =  $pricezhdax; // 大写
        //     $items = $data;
        //     // 记录主表filepath
        //     $reshtmodel = $this->formbuilddoc("ff", $items);  //转 doc
        // }
        // // var_dump( $reshtmodel );die;
        // // 发的发的发
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 也是需要编辑明细的D表  这个回头在说
     *
     */
    public function editContract()
    {

        $com = new CommonPlus();
        $id = input('id');
        $id_zs = input('id_zs'); //展商id
        $model_id = input('model_id'); // 获取选择的合同模版
        $id_zhui = input('id_zhui'); //展位id
        $contractRes=db('contract')->where(['id'=>$id])->find();
        if (!$contractRes) {
            return json(['code' => 0, 'msg' => '参数有误，请核查']);
        }
        $temp=db('contract_mould_yc')->where(['id'=>$model_id])->find();
        if(!$temp){
            return json(['code' => 0, 'msg' => '操作失败，未上传模板']);
        }
        if(empty($id_zs)){
            return json(['code' => 0, 'msg' => '操作失败，未选择展商']);
        }
        if(empty($id_zhui)){
            return json(['code' => 0, 'msg' => '操作失败，未选择展会']);
        }
        $id_zwei = input('id_zwei'); //展位id
        $rBooth=db('booth')->where(['is_delete'=>0,'id'=>array('in',$id_zwei)])->field('id,agent_id')->select();
        if(count($rBooth)!=count(explode(',',$id_zwei))){
            return json(['code' => 0, 'msg' => '操作失败，展位错误']);
        }

        $flag=true;
        foreach($rBooth as &$v){
            if($id_zs!=$v['agent_id']){
                $flag=false;
                break;
            }
        }
        if($flag == false){
            return json(['code' => 0, 'msg' => '展商绑定展位错误']);
        }
        //==common
        $create_uid = $this->admin['id'];
        $remark = input('remark');
        //== comon
        $name_zs = input('name_zs'); //展商名称:
        $addr = input('addr');
        $tel = input('tel');
        $fax = input('fax');  // 传真
        $people_jinban = input('people_jinban'); //经办人
        $type_canzhan = input('type_canzhan'); // 参展展品类别
        $ht_name = input('ht_name'); // 合同名称
        $people_qianyue = input('people_qianyue'); // 签约人
        $customername = input('customername'); // 客户名称
        $ht_time = strtotime(input('ht_time')); // 合同日期
        $ht_time_endpay = strtotime(input('ht_time_endpay')); // 付款截止日期
        $money_total_xiangmu = input('money_total_xiangmu'); // 项目总金额
        $money_zhuce = input('money_zhuce'); // 注册费
        $money_total_ht = input('money_total_ht'); // 合同总金额
        $pay_planname = input('pay_planname'); // 付款计划名称
        $money_pay_one = input('money_pay_one'); // 单笔支付
        $money_pay_total_fk = input('money_pay_total_fk'); // 付款总额
        $time_pay_endfk = strtotime(input('time_pay_endfk')); // 付款截至日期
        $per_fk = input('per_fk'); // 付款比例
        $link=input('link'); // 网址
        $positions_cn=input('positions_cn'); // 职位
        $email_person=input('email_person'); // email
        $business_type=input('business_type'); // 公司性质
        $mobile_person=input('mobile_person'); // 移动电话
        $corner_price=input('corner_price'); // 角摊费用
        $postcode=input('postcode'); // 角摊费用
        $data = array(
            'create_uid' => $create_uid, 'remark' => $remark, 'create_time' => time(),'model_id'=>$model_id,'corner_price'=>$corner_price,'postcode'=>$postcode,
            'name_zs' => $name_zs, 'id_zs' => $id_zs, 'id_zhui' => $id_zhui,'ht_id' => $temp['template_code'].$id_zhui.$id_zs, 'id_zwei'=>$id_zwei,'addr' => $addr, 'tel' => $tel, 'fax' => $fax,
            'people_jinban' => $people_jinban, 'type_canzhan' => $type_canzhan, 'ht_name' => $ht_name, 'people_qianyue' => $people_qianyue,
            'customername' => $customername, 'ht_time' => $ht_time, 'ht_time_endpay' => $ht_time_endpay, 'money_total_xiangmu' => $money_total_xiangmu, 'money_zhuce' => $money_zhuce,
            'money_total_ht' => $money_total_ht, 'pay_planname' => $pay_planname, 'money_pay_one' => $money_pay_one, 'money_pay_total_fk' => $money_pay_total_fk, 'time_pay_endfk' => $time_pay_endfk,
            'per_fk' => $per_fk,'link' => $link,'s_status'=>0,'positions_cn'=>$positions_cn,'email_person'=>$email_person,'business_type'=>$business_type,'mobile_person'=>$mobile_person
        );


        // $data11 = array(
        //     'create_uid' => $create_uid, 'remark' => $remark, 'update_time' => time(),
        //     'name_zs' => $name_zs, 'addr' => $addr, 'tel' => $tel, 'fax' => $fax,
        //     'people_jinban' => $people_jinban, 'type_canzhan' => $type_canzhan, 'ht_id' => $ht_id, 'ht_name' => $ht_name, 'people_qianyue' => $people_qianyue,
        //     'customername' => $customername, 'ht_time' => $ht_time, 'ht_time_endpay' => $ht_time_endpay, 'money_total_xiangmu' => $money_total_xiangmu, 'money_zhuce' => $money_zhuce,
        //     'money_total_ht' => $money_total_ht, 'pay_planname' => $pay_planname, 'money_pay_one' => $money_pay_one, 'money_pay_total_fk' => $money_pay_total_fk, 'time_pay_endfk' => $time_pay_endfk,
        //     'per_fk' => $per_fk
        // );
        $changeMeg='';$conType='';
        if($contractRes['id_zwei']!=$id_zwei){
            $changeMeg.="展位由".$contractRes['id_zwei']."变更为".$id_zwei;
            $conType=3;
        }else{
            $conType=2;
            if($contractRes['money_total_ht']!=$money_total_ht){
                $changeMeg.="金额由".$contractRes['money_total_ht']."变更为".$money_total_ht;
            }
            if(!$changeMeg){$changeMeg.='其它修改';}
        }
        $com->contractLog($id_zhui,$changeMeg,$id_zs,$conType);

        $where['id'] = $id;
        $r = $this->model->updateBywhere($data, $where);


        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }



        // // 明细 开始

        // /**
        //  * 服务类别  下拉框 还是文本框？？？
        //  * sort 是永远 递增
        //  */


        // //增加明细   包含更新
        // $detaildata1 = input('D_detail'); // 数组
        // // $detaildata = json_decode(json_encode(($detaildata22)),TRUE);
        // $detaildata = json_decode($detaildata1, TRUE);
        // // var_dump($detaildata);die;
        // $detaildata = 0;
        // $z_id = $id; // 主id
        // if (is_array($detaildata)) {
        //     $i = 0;
        //     foreach ($detaildata as $item) {
        //         $i++;
        //         $data_d = array(
        //             'is_delete'=>0,
        //             'mid' => $z_id, 'sortid' => $i, 'pro_name' => $item['pro_name'], 'type1_name' => $item['type1_name'],'isck' => $item['isck'],
        //             //'type_serviceid' => $item['type_serviceid'],
        //             'type_service' => $item['type_service'], 'price' => $item['price'],
        //             'price_sale' => $item['price_sale'], 'discount' => $item['discount'], 'num' => $item['num'], 'price_prate' => $item['price_prate'],
        //             'price_count' => $item['price_count'], 'remark' => $item['remark']
        //         );
        //         $r1 = $this->model->insertData_D($data_d, 'contract_detail'); //暂未定


        //     }
        // }
        // // 明细end

        // // 计划明细
        // $plan_detail22 = array(
        //     array("plan_name" => "plan_name", "money_db" => "11", "money_total" => "20", "time_fked" => "111", "per_fk" => "7" ),
        //     array("plan_name" => "plan_name", "money_db" => "11", "money_total" => "20", "time_fked" => "111", "per_fk" => "8" ),
        // );

        // //增加明细   包含更新

        // // $plan_detail = json_decode(json_encode(($plan_detail22)),TRUE); // ces
        // $plan_detail1 = input('plan_detail'); // 数组
        // $plan_detail = json_decode($plan_detail1, TRUE);
        // $plan_detail = 0; // 走单独的小按钮保存

        // if (is_array($plan_detail)) {
        //     $i = 0;
        //     foreach ($plan_detail as $item) {
        //         $i++;
        //         $data_d = array(
        //             'is_delete'=>0,
        //             'mid' => $z_id, 'sortid' => $i, 'plan_name' => $item['plan_name'], 'money_db' => $item['money_db'],
        //             'money_total' => $item['money_total'], 'time_fked' => strtotime($item['time_fked']), 'per_fk' => $item['per_fk']
        //         );
        //         $r2 = $this->model->insertData_D($data_d, 'contract_detail_plan'); // coms


        //     }
        // }
        // // 明细end


        // // 0404 测试  查询展位


        // $where = array('id' => $id_zwei);
        // $rzw = $com->sel_com_fxlist("f", $where, "booth");

        // // $pricezh=$com->convertAmountToCn($rzw[0]['price'],0);
        // $pricezhdax=$com->inttod($rzw[0]['price'],0);
        // $zspara=array('id_zs'=>$id_zs); // zhans
        // $info_zs= $com->getinfo_zs( $zspara);// 展商id...

        // // 0404



        // // 根据模版 转doc 2：回头在更新主表new file
        // if (!empty($htmodel)) {
        //     $items['htmodel'] = $htmodel;
        //     $items['z_id'] = $r;
        //     // 0404
        //     // 展商信息 可能又重复数组 覆盖，排查
        //     $items['company_name'] = $info_zs[0]['company_name']; //
        //     $items['company_name_en'] = $info_zs[0]['company_name_en']; //
        //     $items['company_address'] = $info_zs[0]['company_address']; //
        //     $items['company_yb'] = $info_zs[0]['company_yb']; //   邮编
        //     $items['link'] = $info_zs[0]['link']; //
        //     $items['salesman'] = $info_zs[0]['salesman']; //   负责人 暂时业务员
        //     $items['positions'] = $info_zs[0]['positions']; //    职务
        //     $items['tel'] = $info_zs[0]['tel']; //
        //     $items['mobile'] = $info_zs[0]['mobile']; //
        //     $items['fax_person'] = $info_zs[0]['fax_person']; //     传真
        //     $items['email'] = $info_zs[0]['email']; //


        //     //2
        //     $items['area'] = $rzw[0]['area']; // 面积
        //     $items['price'] = $rzw[0]['price'];
        //     $items['price_count'] = $rzw[0]['price'];
        //     $items['price_daxie'] =  $pricezhdax; // 大写
        //     // 记录主表filepath
        //     $res = $this->formbuilddoc("ff", $items);  //转 doc


        // }


        return json(['code' => 1, 'msg' => '操作成功']);
    }


    /**
     * 合同删除
     * 删除财务记录、释放展位、删除合同、更改展商状态、删除展商密码和账户
     * 这边应该也会关联很多  后续考虑 stj
     * @return \think\response\Json|void
     */
    public function resDelContract(){
        $com = new CommonPlus();
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
                $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
                if(!$exRes){
                    return json(array('code' => '0', 'msg' => '展会信息错误'));
                }
                $conRes=db('contract')->where(['id'=>$id,'is_delete'=>0])->find();
                if(!$conRes){
                    return json(array('code' => '0', 'msg' => '合同信息错误'));
                }
                $tabName=$this->getTabName($conRes['id_zhui']);
                $zsData = db($tabName)->where(['id'=>$conRes['id_zs']])->find();
                if(!$zsData){
                    return json(['code'=>0,'msg'=>'展商数据错误']);
                }

                //开始事务
                //删除财务记录
                $financeArr =db('finance')->field('id')->where(['contract_id'=>$id,'is_delete'=>0])->select();
                if(!empty($financeArr)){
                    $ids=[];
                    foreach ($financeArr as &$v) {
                        $ids[]=$v['id'];
                    }
                    $fWhere['id'] = array('in',implode(',',$ids));
                    $fRes=db('finance')->where($fWhere)->update(['is_delete'=>1]);
                    if(false === $fRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,财务记录未删除'));
                    }
                }

                //释放展位
                if($conRes['id_zwei']){
                    $bWhere['id'] = array('in',$conRes['id_zwei']);
                    $bWhere['is_delete'] = 0;
                    $bRes=db('booth')->where($bWhere)->update(['agent_id'=>null]);
                    if(false === $bRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,展位未释放成功'));
                    }
                }

                //更改展商状态并删除账号密码
                $zsRes = db($tabName)->where(['id'=>$conRes['id_zs']])->update(['status'=>0,'account'=>null,'pwd'=>null,'update_time'=>time()]);
                if(false === $zsRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,展商未修改成功'));
                }


                //删除合同
                $cRes=db('contract')->where(['id'=>$id])->update(['is_delete'=>1]);
                if(false === $cRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,合同未删除成功'));
                }
                //删除缓存数据
                db('company_storage')->where(['exhibition_id'=>$exhibition_id,'company_id'=>$id])->delete();
                $com->contractLog($exhibition_id,'合同删除',$conRes['id_zs'],4);
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 合同退回
     * 删除财务记录、释放展位、删除合同、更改展商状态、删除展商密码和账户
     * 这边应该也会关联很多  后续考虑 stj
     * @return \think\response\Json|void
     */
    public function resBackContract(){
        $com = new CommonPlus();
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
                $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
                if(!$exRes){
                    return json(array('code' => '0', 'msg' => '展会信息错误'));
                }
                $conRes=db('contract')->where(['id'=>$id,'is_delete'=>0])->find();
                if(!$conRes){
                    return json(array('code' => '0', 'msg' => '合同信息错误'));
                }
                $tabName=$this->getTabName($conRes['id_zhui']);
                $zsData = db($tabName)->where(['id'=>$conRes['id_zs']])->find();
                if(!$zsData){
                    return json(['code'=>0,'msg'=>'展商数据错误']);
                }

                //开始事务
                //删除财务记录
                $financeArr =db('finance')->field('id')->where(['contract_id'=>$id,'is_delete'=>0])->select();
                if(!empty($financeArr)){
                    $ids=[];
                    foreach ($financeArr as &$v) {
                        $ids[]=$v['id'];
                    }
                    $fWhere['id'] = array('in',implode(',',$ids));
                    $fRes=db('finance')->where($fWhere)->update(['is_delete'=>1]);
                    if(false === $fRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,财务记录未删除'));
                    }
                }
                //释放展位
                if($conRes['id_zwei']){
                    $bWhere['id'] = array('in',$conRes['id_zwei']);
                    $bWhere['is_delete'] = 0;
                    $bRes=db('booth')->where($bWhere)->update(['agent_id'=>null]);
                    if(false === $bRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,展位未释放成功'));
                    }
                }

                //更改展商状态,账号密码保留
                $zsRes = db($tabName)->where(['id'=>$conRes['id_zs']])->update(['status'=>0]);
                if(false === $zsRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,展商未修改成功'));
                }


                //更改合同状态，改为退回
                $cRes=db('contract')->where(['id'=>$id])->update(['s_status'=>3,'id_zwei'=>0,'ht_id'=>null,'ht_name'=>null,'htmodel_admin'=>'','htmodel'=>'']);
                if(false === $cRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,合同状态未更改成功'));
                }
                $com->contractLog($exhibition_id,'合同删除',$conRes['id_zs'],4);
                //删除缓存数据
                db('company_storage')->where(['exhibition_id'=>$exhibition_id,'company_id'=>$id])->delete();
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     * 更改合同展位
     * 1：退出以前展位
     * 2：重新添加展位
     */
    public function contractChangeBooth(){
        $com = new CommonPlus();
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
                $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
                if(!$exRes){
                    return json(array('code' => '0', 'msg' => '展会信息错误'));
                }

                $id = isset($post['contract_id']) && $post['contract_id'] != '' ? $post['contract_id'] : 0;
                $conRes=db('contract')->where(['id'=>$id,'is_delete'=>0])->find();
                if(!$conRes){
                    return json(array('code' => '0', 'msg' => '合同信息错误'));
                }
                $company_id = isset($post['company_id']) && $post['company_id'] != '' ? $post['company_id'] : 0;
                $tabName=$this->getTabName($exhibition_id);
                $zsData = db($tabName)->where(['id'=>$company_id])->find();
                if(!$zsData){
                    return json(['code'=>0,'msg'=>'展商数据错误']);
                }
                $booth_ids=isset($post['booth_ids']) && $post['booth_ids'] != '' ? $post['booth_ids'] : null;
                if(!$booth_ids){
                    return json(['code'=>0,'msg'=>'未选择展位']);
                }
                $boothComList=db('booth')->where(['id'=>array('in',$booth_ids),'is_delete'=>0])->select();
                if(count($boothComList)!=count(explode(",", $booth_ids))){
                    return json(['code'=>0,'msg'=>'展位信息错误']);
                }
                $megs=null;
                foreach ($boothComList as &$v) {
                    if($v['agent_id']>0){
                        $megs=$v['number'].'展位已被绑定';
                        break;
                    }
                }
                if($megs!=null){
                    return json(['code'=>0,'msg'=>$megs]);
                }

                //开始事务
                //释放展位
                if($conRes['id_zwei']){
                    $bRes=db('booth')->where(['id'=>array('in',$conRes['id_zwei']),'is_delete'=>0])->update(['agent_id'=>null]);
                    if(false === $bRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,展位未释放成功'));
                    }
                }
                //重新绑定展位展商
                $rEditRes=db('booth')->where(['id'=>array('in',$booth_ids),'is_delete'=>0])->update(['agent_id'=>$company_id]);
                if(false === $rEditRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,展位添加失败'));
                }
                //更改合同展位
                $cRes=db('contract')->where(['id'=>$id])->update(['id_zwei'=>$booth_ids]);
                if(false === $cRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,合同状态未更改成功'));
                }
                $com->contractLog($exhibition_id,'展位变更',$conRes['id_zs'],3);
                //删除缓存数据
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 删除项目
     * 1：列表 删除 是不是同时要删除子表。这个是大的删除
     * 2：合同主项 里面要依次删除呢？需要重写方法fsd
     */
    public function delContract()
    {
        $id = input('id');
        if(empty($id)){
            return json(['code' => 0, 'msg' => '缺少关键主键合同id']);
        }
        $where = ['id' => $id];
        $info = $this->model->where($where)->find();
        if (empty($info)) {
            return json(['code' => 0, 'msg' => '记录不存在，请核实']);
        };
        if($info['s_status'] == 0 || $info['s_status'] == 1){
            return json(['code' => 0, 'msg' => '合同审核或未完成无法此操作']);
        }
        if($info['create_uid'] != $this->admin['id']){
            return json(['code' => 0, 'msg' => '你不是合同创建者无法此次操作']);
        }
        $r = $this->model->deleteWhere(['id' => $id]);
        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }



    /**
     * 合同 明细 副表 走单独接口 明细
     * @return \think\response\Json|void
     */
    public function editContract_d_ht()
    {
        $com = new CommonPlus();
        $formtype = input('formtype'); // 表类型 no go
        $mid= input('mid');
        $sortid = input('sortid');

        $updates = array(
            'issort'=>1,'mid'=>$mid,
            'pro_name' => input('pro_name'), 'type1_name' =>input('type1_name'),
            'type_service' => input('type_service'), 'price' =>  input('price'),
            'price_sale' =>  input('price_sale'), 'discount' =>  input('discount'),
            'num' =>  input('num'), 'price_prate' =>  input('price_prate'),
            'price_count' =>  input('price_count'), 'remark' => input('remark')
        );


        $where1 = array('mid' => $mid,'sortid'=>$sortid);
        $dbname="contract_detail";

        $r = $com->insert_com_fxlist( $updates, $where1,  $dbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => 'success']);
    }

    /**
     * 合同 明细 副表 走单独接口 明细 dd
     * @return \think\response\Json|void
     * 计划名称|单笔支付\money_total|付款截止日期|付款比例
     */
    public function editContract_d_plan()
    {
        $com = new CommonPlus();
        $formtype = input('formtype'); // 表类型 no go
        $mid= input('mid');
        $sortid = input('sortid');

        $updates = array(
            'issort'=>1,'mid'=>$mid,
            'plan_name' => input('plan_name'), 'money_db' =>input('money_db'),
            'money_total' => input('money_total'), 'time_fked' =>  strtotime(input('time_fked')),
            'per_fk' => input('per_fk')
        );


        $where1 = array('mid' => $mid,'sortid'=>$sortid);
        $dbname="contract_detail_plan";

        $r = $com->insert_com_fxlist( $updates, $where1,  $dbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => 'success']);
    }


    /**
     * 审核合同
     */
    public function checkContract(){
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'缺少关键主键合同id']);
        }
        $info = db('contract')->where(['id'=>$id])->find();
        if(!$info){
            return json(['code'=>0,'msg'=>'记录不存在']);
        }
        if(!$info['htmodel_admin']){
            return json(['code'=>0,'msg'=>'盖章合同未上传']);
        }
        $status=$this->request->param('status');
        $data=array();
        if(isset($status)){
            $data['s_status'] = intval($status);
        }
        $back=$this->request->param('back');
        if(isset($back)){
            $data['is_back'] = intval($back);
        }
        $remark=$this->request->param('remark');
        if(isset($remark)){
            $data['remarks'] = $remark;
        }
        $tabName=$this->getTabName($info['id_zhui']);
        $zsData = db($tabName)->where(['id'=>$info['id_zs']])->find();
        if(!$zsData){
            return json(['code'=>0,'msg'=>'展商数据错误,操作失败，请重试']);
        }

        $r = db('contract')->where(['id'=>$id])->update($data);
        if(!$r){
            return json(['code'=>0,'msg'=>'合同状态操作失败，请重试']);
        }
//        #添加操作记录
//        try {
//            $logData['follow_id'] = $info['id'];
//            $logData['public_id'] = db($tabName)->where(['id'=>$info['id_zs']])->value('company_id1');
//            $logData['member_id'] = $info['create_uid'];
//            $logData['content'] = $this->admin['realname'].'操作合同审核，由'.$this->statusArr[$info['s_status']].'变更为'.$this->statusArr[($data['s_status']?$data['s_status']:1)];
//            $r = setFollowLog($logData);
//
//        } catch (\Exception $e) {
//
//        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }


    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }






    /**
     * 合同删除 明细
     * formtype
     * 这边应该也会关联很多  后续考虑 stj
     * @return \think\response\Json|void
     */
    public function delContract_d_com()
    {
        $com = new CommonPlus();
        $formtype = input('formtype'); // 表类型
        $mid= input('mid');
        $sortid = input('sortid');

        if(empty($formtype)){
            return json(['code' => 0, 'msg' => '缺少参数fromtype']);
        }

        $where1 = array('mid' => $mid,'sortid'=>$sortid); //保持一致
        $updates= array('is_delete' => 1); //保持一致

        $dbname="";
        if($formtype=="d_ht"){
            // 合同明细d
            $dbname="contract_detail";
        }elseif($formtype=="d_plan"){
            //  计划明细d
            $dbname="contract_detail_plan";
        }

        $r = $com->edit_com_fxlist( $updates, $where1,  $dbname);

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        // var_dump($r1);die;

        return json(['code' => 1, 'msg' => 'success']);
    }

    /**
     * 支持单独的子表操作
     * 是否在页面添加按钮 允许此操作？？
     * 赞不开启
     *
     */
    public function delContract_d()
    {

        $mid = input('mid');
        $sortIds = input('sortids');
        foreach ($sortIds as $item) {
            $r = $this->model->deleteWhere_d(['sortid' => $item, 'mid' => $mid]);
        }

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }
    /**
     *  查询合同模版列表 供存档用
     * 主要  添加合同要生成模版。有新模版就继续手动编辑变量。然后 上传 追来源
     * com sel  一些基础传参
     */
    public function sel_htmode()
    {
        $com = new CommonPlus();
        $where = array('is_delete' => 0);
        $r = $com->sel_com_fxlist("f", $where, "contract_mould_yc");

        if (!$r) {
            return json(['code' => 0, 'msg' => '操作失败，请重试']);
        }

        return json(['code' => 1, 'msg' => '操作成功', 'data' => $r]);
    }

    /**
     * 生成合同模版 新增调用
     * ${keti} tag
     * 替换 形成 新文件，并更新主表 存储 log
     * 前端应该下拉框与后台保持一致；
     *
     */
    public function formbuilddoc($items)
    {
        $doc = new CommonPlus();
        $filenewname = 'ht'.time().'.docx';
        $res = $doc->dobuildDoc("HT", $filenewname, $items);
        if($res['info']==null || $res['info']=='null'){
            return array('code' => '1', 'msg' => '成功','data'=>$res['model_newfile']);
        }
        return array('code' => '0', 'msg' => '失败');
    }




    /**
     * 生成合同模版 测试用
     * ${keti} tag
     * 替换 形成 新文件，
     * 前端应该下拉框与后台保持一致；
     */
    public function builddoc()
    {
        $doc = new CommonPlus();
        $Billno = $doc->createNO('HT-', 1);
        $filenewname = $Billno . '.docx';
        $comptype = "DZ";
        $comptype1 = $comptype == "MY" ? "Y" : "";
        $comptype2 = $comptype == "HZ" ? "Y" : "";
        $comptype3 = $comptype == "DZ" ? "Y" : "";
        $type = "HT";
        $HTfile = array('modelfile' => '2019PLF-biaogaite.docx', 'newfile' => $filenewname);
        // 传参数过去 替换
        $params = array(
            "company_name" => "苏州光辉", "company_name_en" => "suzhouugnagh", "company_address" => "苏州相城",
            "contact" => "张三", "link" => "www.baidu", "positions" => "科长", "email" => "184511852@qq.com",
            "tel" => "17625010777", "mobile" => "17625010778", "comptype1" => $comptype1, "comptype2" => $comptype2, "comptype3" => $comptype3
        );

        $isfile = $doc->checkHTmodelfile($type, $HTfile['modelfile']);
        // var_dump($isfile);die;
        // $isfile=2;
        if ($isfile > 0) {
            $res = $doc->dobuildDoc($type, $HTfile, $params);
            if ($res) {
                return json(['code' => 0, 'msg' => '合同生成失败']);
            } else {
                return json(['code' => 1, 'msg' => '合同生成成功']);
            }
        } else {
            return json(['code' => 0, 'msg' => '合同模板不存在']);
        }
    }


    // 测试
    public function companyList_shaixuan_ces()
    {
        //基础公司表
        //个人信息 中文姓名 职务 部门 手机 数据来源 所属洲 国家 省份 城市  公司中文名 地址 网址 固定电话 一级分类 二级分类
        //$keyword = $this->request->param('keyword');
        $page = $this->request->param('page');
        $where = array();
        $page = max(1, intval($page));
        $pagesize = 200;
        $where['is_delete'] = 0; //回头问下
        $exhibition_id = $this->request->param('exhibition_id');//展会id
        if(empty($exhibition_id)){
            return json(['code' => 0, 'msg' => '缺少关键主键展会id']);
        }
        // 查询 st 精确查询还是模糊 查询。。。。擦  都是必要的字段留着 其他的没卵用
        $name_cn = $this->request->param('name_cn'); //中文姓名
        $positions_cn = $this->request->param('positions_cn'); //职务
        $department_cn = $this->request->param('department_cn'); //职务
        $mobile = $this->request->param('mobile'); //手机
        $data_from = $this->request->param('data_from'); //数据来源
        $country = $this->request->param('country');//国家
        $province = $this->request->param('province');  //省份
        $area_city = $this->request->param('area_city');  //地级市
        $company_name = $this->request->param('company_name'); //公司中文名
        $tel = $this->request->param('tel');   //固定电话
        $link = $this->request->param('link'); //网址
        $category_id = $this->request->param('category_id');  //一级 分类
        $second_category_id = $this->request->param('second_category_id');     //二级 分类

        if(!empty($name_cn)){
            $where['name_cn'] = array('like', '%' . $name_cn . '%');
        }

        if(!empty($positions_cn)){
            $where['positions_cn'] = array('like', '%' . $positions_cn . '%');
        }

        if(!empty($department_cn)){
            $where['positions_cn'] = array('like', '%' . $department_cn . '%');
        }

        if(!empty($mobile)){
            $where['mobile'] = $mobile;
        }

        if(!empty($data_from)){
            $where['data_from'] = array('like', '%' . $data_from . '%');
        }

        if(!empty($country)){
            $where['data_from'] = array('like', '%' . $country . '%');
        }

        if(!empty($province)){
            $where['data_from'] = array('like', '%' . $province . '%');
        }

        if(!empty($area_city)){
            $where['data_from'] = array('like', '%' . $area_city . '%');
        }

        if(!empty($company_name)){
            $where['company_name'] = array('like', '%' . $company_name . '%');
        }

        if(!empty($tel)){
            $where['tel'] = $tel;
        }

        if(!empty($link)){
            $where['tel'] = $link;
        }

        if(!empty($category_id)){
            $where['category_id'] = array('like', '%' . $category_id . '%');
        }

        if(!empty($second_category_id)){
            $where['company_name'] = array('like', '%' . $second_category_id . '%');
        }
        $list =db('company')->field('id,company_name')->where($where)->order('id desc')->limit(($page-1)*$pagesize.','.$pagesize)->select();
        $total=db('company')->where($where)->count();
        $w['exhibition_id'] = $exhibition_id;
        $newList=array();
        //1; 2；排除 企业库 存在于 公海的数据 200526

        foreach($list as &$val){
            $w['company_id']=$val['id'];
            $ls = $this->model->field('company_id')->where($w)->select();
            if(empty($ls)){
                $val['is_pub']=0;
                $newList[]=$val;
            }else{
                //$val['is_pub']=1;
            }
        }
        unset($val);
        $list=$newList;  //st
        $total=count($list); //st
        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list, 'total' => $total]]);
    }




    //生成合同模板并且下载
    //生成合同模板并且下载
    public function contractemDown(){
        if (request()->isPost()) {
            $com = new CommonPlus();
            $post = input('post.');
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;//模板id
            $company_id = isset($post['company_id']) && $post['company_id'] != '' ? $post['company_id'] : 0;//展商id
            $contract_id = isset($post['contract_id']) && $post['contract_id'] != '' ? $post['contract_id'] : 0;//合同id
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;//展会id
            $exhibitionRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
            if(!$exhibitionRes){
                return json(['code'=>0,'msg'=>'展会数据有误']);
            }
            $temp=db('contract_mould_yc')->where(['id'=>$id])->find();
            if(!$temp || !$temp['value']){
                return json(['code'=>0,'msg'=>'合同模板有误']);
            }
            $tabName=$this->getTabName($exhibition_id);
            $companyRes=db($tabName)->where(['id'=>$company_id])->find();
            if(!$companyRes){
                return json(['code'=>0,'msg'=>'展扇信息有误！']);
            }
            $contractRes=db('contract')->where(['id'=>$contract_id])->find();
            if(!$contractRes){
                return json(['code'=>0,'msg'=>'合同信息有误']);
            }
            $position=Db::name('booth')
                ->alias('b')
                ->field('b.area,b.price,b.corner_stall,b.price_type,m.title as type_title')
                ->join('crm_booth_mold m','m.id=b.price_type','left')
                ->where(['b.id'=>['in',$contractRes['id_zwei']],'b.is_delete'=>0])
                ->select();
            // 根据模版 转doc 2：回头在更新主表new file
            $items['htmodel'] = $temp['value'];
            $items['company_name'] = $companyRes['company_name'];
            $items['company_name_en'] = $companyRes['company_name_en'];
            $items['company_address'] = $contractRes['addr'];
            $items['positions_cn'] = $contractRes['positions_cn'];
            $items['template_code'] = $contractRes['ht_id'];
            $items['postcode'] = $contractRes['postcode'];
            $items['link'] = $contractRes['link'];
            $items['people_jinban'] = $contractRes['people_jinban'];
            $items['mobile_person'] = $contractRes['mobile_person'];
            $items['tel'] = $contractRes['tel'];
            $items['fax'] = $contractRes['fax'];
            $items['email_person'] = $contractRes['email_person'];
            $items['money_total_ht'] = $contractRes['money_total_ht'];
            $items['comptype3'] = $contractRes['business_type'] == "独资" ? "☑" : "□";
            $items['comptype2'] = $contractRes['business_type'] == "合资" ? "☑" : "□";
            $items['comptype1'] = $contractRes['business_type'] == "民营" ? "☑" : "□";
            $items['exhibition_address'] = $exhibitionRes['exhibition_address'];
            $stime=strtotime($exhibitionRes['starttime']);
            $etime=strtotime($exhibitionRes['endtime']);
            $datearr = [];
            while ($stime <= $etime) {
                $a=date("Y年m月d日", $stime);
                $datearr[] = $a;//得到dataarr的日期数组。
                $stime = $stime + 86400;
            }
            $items['exhibition_time'] =current($datearr)."-".end($datearr);
            $area=0;$price=0;$corner_price=0;$type_title='';
            if(count($position)>0){
                foreach ($position as &$v){
                    $area+=$v['area'];
                    $price+=$v['price'];
                    $corner_price+=$v['corner_stall'];
                    $type_title.=$v['type_title'].' ';
                }
                $items['area'] = $area;
                $items['price'] = $price;
                $items['hall_title'] = $type_title;
                $items['price_daxie']=$com->inttod($contractRes['money_total_ht']);
                $items['corner_price'] = $corner_price>0?$corner_price:'';
                $advance_charge_num=$contractRes['money_total_ht']-3000;
                $items['advance_charge_num'] = sprintf("%.2f",($advance_charge_num>0?$advance_charge_num:0));
                $items['advance_charge_text'] = $com->inttod($items['advance_charge_num']);
            }
            $res = $this->formbuilddoc($items);  //转 doc
            return json($res);
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    //作废合同
    public function contractToVoid(){
        $com = new CommonPlus();
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : 0;
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
                $exRes=db('exhibition')->where(['id'=>$exhibition_id])->find();
                if(!$exRes){
                    return json(array('code' => '0', 'msg' => '展会信息错误'));
                }
                $conRes=db('contract')->where(['id'=>$id,'is_delete'=>0])->find();
                if(!$conRes){
                    return json(array('code' => '0', 'msg' => '合同信息错误'));
                }
                $tabName=$this->getTabName($conRes['id_zhui']);
                $zsData = db($tabName)->where(['id'=>$conRes['id_zs']])->find();
                if(!$zsData){
                    return json(['code'=>0,'msg'=>'展商数据错误']);
                }

                //开始事务
                //释放展位
                if($conRes['id_zwei']){
                    $bWhere['id'] = array('in',$conRes['id_zwei']);
                    $bWhere['is_delete'] = 0;
                    $bRes=db('booth')->where($bWhere)->update(['agent_id'=>null]);
                    if(false === $bRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,展位未释放成功'));
                    }
                }

                //更改关联展位更改状态
                $cRes=db('contract')->where(['id'=>$id])->update(['s_status'=>4,'id_zwei'=>0,'htmodel_admin'=>'','htmodel'=>'']);
                if(false === $cRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,合同未作废成功'));
                }
                //删除缓存数据
                db('company_storage')->where(['exhibition_id'=>$exhibition_id,'company_id'=>$id])->delete();
                $com->contractLog($exhibition_id,'合同作废',$conRes['id_zs'],5);
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function contractAgeUpload(){
        if (request()->isPost()) {
            $post = input('post.');
            $contract_id = isset($post['contract_id']) && $post['contract_id'] != '' ? $post['contract_id'] : 0;//合同id
            $file = isset($post['file']) && $post['file'] != '' ? $post['file'] : null;//合同id
            $contractRes=db('contract')->where(['id'=>$contract_id])->find();
            if(!$contractRes){
                return json(['code'=>0,'msg'=>'合同信息有误']);
            }
            if(!$file){
                return json(['code'=>0,'msg'=>'上传合同信息有误']);
            }
            $res=db('contract')->where(['id'=>$contract_id])->update(['htmodel_admin'=>$file]);
            if(!$res){
                return json(array('code' => '0', 'msg' => '操作失败'));
            }
            return json(array('code' => '1', 'msg' => '操作成功'));
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    //
    public function letterConfirmation (){
        if (request()->isPost()) {
            $post = input('post.');
            $contract_id = isset($post['contract_id']) && $post['contract_id'] != '' ? $post['contract_id'] : 0;//合同id
            $file = isset($post['file']) && $post['file'] != '' ? $post['file'] : null;//合同id
            $contractRes=db('contract')->where(['id'=>$contract_id])->find();
            if(!$contractRes){
                return json(['code'=>0,'msg'=>'合同信息有误']);
            }
            if(!$file){
                return json(['code'=>0,'msg'=>'上传合同附件有误']);
            }
            $res=db('contract')->where(['id'=>$contract_id])->update(['confirmation_file'=>$file]);
            if(!$res){
                return json(array('code' => '0', 'msg' => '操作失败'));
            }
            return json(array('code' => '1', 'msg' => '操作成功'));
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function contractGZUpload(){
        if (request()->isPost()) {
            $post = input('post.');
            $contract_id = isset($post['contract_id']) && $post['contract_id'] != '' ? $post['contract_id'] : 0;//合同id
            $file = isset($post['file']) && $post['file'] != '' ? $post['file'] : null;//合同id
            $contractRes=db('contract')->where(['id'=>$contract_id])->find();
            if(!$contractRes){
                return json(['code'=>0,'msg'=>'合同信息有误']);
            }
            if(!$file){
                return json(['code'=>0,'msg'=>'上传合同信息有误']);
            }
            $res=db('contract')->where(['id'=>$contract_id])->update(['htmodel'=>$file]);
            if(!$res){
                return json(array('code' => '0', 'msg' => '操作失败'));
            }
            return json(array('code' => '1', 'msg' => '操作成功'));
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function wordtopdf()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $url = isset($post['url']) && $post['url'] != '' ? $post['url'] : '';//合同id
            $file=ROOT_PATH.'public/uploads/word/'.$url;
            //检查文件是否存在
            if(!file_exists($file)){
                return array('code' => '0', 'msg' => '生成文件不存在!');
            }
            $filename=basename($url);
            $request = Request::instance();
            $domain = $request->domain();
            $fileUrl=$domain.'/public/uploads/word/'.$url;
            $para=array('url'=>$fileUrl,'filename'=>$filename);
            $res=$this->wordtopdfali($para);
//            var_dump($res);die();
            if($res && $res['code']==1){
                return json(array('code' => '1', 'msg' => '成功','data'=>$res['data']));
            }
            return json(array('code' => '0', 'msg' => '下载失败'));
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function wordtopdfback(){
        $post = input('post.');
        var_dump($post);
    }


    public function wordstatusback(){
        if (request()->isPost()) {
            $post = input('post.');
            $job_id = isset($post['job_id']) && $post['job_id'] != '' ? $post['job_id'] : '';//合同id
            //检查文件是否存在
            if(!$job_id){
                return array('code' => '0', 'msg' => '数据错误!');
            }
            $res=$this->wordtopdstatus($job_id);
            if($res && $res['code']==1){
                return json(array('code' => '1', 'msg' => '成功','data'=>$res['data']));
            }
            return json(array('code' => '0', 'msg' => '下载失败'));
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function wordtopdstatus($job_id){
        $host = "https://api.docsdk.com";
        $path = "/v2/jobs/".$job_id.'/wait';
        $method = "GET";
        $appcode = "cEcgfXAXmhxFePfduzEoYD2fWzoPMgws2EO7";
        $header = array();
        array_push($header, "Authorization:Bearer  " .$appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($header, "Content-Type".":"."application/json; charset=UTF-8");
        $url = $host . $path;
//        var_dump($url);die();
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        $data=json_decode($data,true);
//        var_dump($data);die();
        curl_close($curl);
        if($data && is_array($data['data']) && count($data['data'])>0){
            return array('code'=>1,'data'=>$data['data']);
        }
        return array('code'=>0);
    }


    public function wordtopdfali($para){
        $host = "https://api.docsdk.com";
        $path = "/v2/jobs";
        $method = "POST";
        $appcode = "cEcgfXAXmhxFePfduzEoYD2fWzoPMgws2EO7";
        $headers = array();
        array_push($headers, "Authorization:Bearer " .$appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $url=$para['url'];
        $bodys = array(
            "tasks"=>array(
                "ImportURL"=>array(
                    "url"=>$url,
                    "operation"=>"import/url"
                ),
                "ConvertFile"=>array(
                    "input"=>[ "ImportURL" ],
                    "output_format"=>"pdf",
                    "operation"=> "convert"
                ),
                "ExportResult"=>array(
                    "input"=> [ "ConvertFile" ],
                    "operation"=>"export/url"
                )
            )
        );
        $bodys=json_encode($bodys);
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $data=curl_exec($curl);
        $data=json_decode($data,true);
        curl_close($curl);
        if($data && is_array($data['data']) && count($data['data'])>0){
            if($data['data']['status'] == 'failed'){
                return array('code'=>0);
            }else{
                return array('code'=>1,'data'=>array('job_id'=>$data['data']['id'],'status'=>$data['data']['status'],'key'=>$appcode));
            }
        }
        return array('code'=>0);
    }


    public function wordtopdfali1($para){
        $host = "http://file.qiyacloud.com";
        $path = "/fileConvert";
        $method = "POST";
        $appcode = "46e8328cca644eb4bbf844f8538bd714";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " .$appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $url=$para['url'];
        $filename=$para['filename'];// 文件名称
        $bodys = "{\"url\":\"$url\",\"fileName\":\"$filename\"}";
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $data=curl_exec($curl);
        curl_close($curl);
        return (json_decode($data,true));
    }
}
